from django.http import JsonResponse
from django.shortcuts import redirect

from vote.settings import LOGIN_REQUIRED_URLS


def check_login_middleware(get_response):

    def middleware(request, *args, **kwargs):
        if request.path in LOGIN_REQUIRED_URLS \
                and request.session.get('userid') is None:
            if request.is_ajax():
                return JsonResponse({'code': 10002, 'message': '请先登录'})
            else:
                return redirect('/login/?hint=请先登录')
        response = get_response(request, *args, **kwargs)
        return response

    return middleware
